<?php

namespace app\common\model\xiservice;

use app\common\model\xiservice\Benfit as BenfitModel;
use app\common\model\xiservice\Comment as CommentModel;
use app\common\model\xiservice\Schedule as ScheduleModel;
use app\common\model\xiservice\User as XiserviceUser;
use think\Db;
use think\Exception;
use think\Model;


class VipOrder extends Model
{


    // 表名
    protected $name = 'xiservice_vip_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'pay_status_text',
        'type_text'
    ];


    public function getPayStatusList()
    {
        return ['10' => __('Pay_status 10'), '20' => __('Pay_status 20')];
    }

    public function getTypeList()
    {
        return ['1' => __('Type 1'), '2' => __('Type 2')];
    }


    public function getPayStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_status']) ? $data['pay_status'] : '');
        $list = $this->getPayStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'user_id', [], 'LEFT')->setEagerlyType(0);
    }


    /**
     * 创建订单
     * @param $data
     * @param $uid
     * @return array
     */
    public function createorder($data, $uid)
    {

        Db::startTrans();
        $orderNo = 'VP' . date("YmdHis") . mt_rand(1000, 9999) . $uid;
        try {
            $data['user_id'] = $uid;
            $data['order_no'] = $orderNo;
            $res = $this->allowField(true)->save($data);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ["status" => false, "data" => [], "msg" => $e->getMessage()];
        }

        $res = $this->where('order_no', $orderNo)->find();
        return ["status" => true, "data" => $res['id'], "msg" => "创建订单成功"];
    }

    /**
     * 修改订单状态
     * @param $id
     * @param $status
     * @return array
     */
    public function changeOrderStatus($id, $status)
    {

        $orderInfo = $this->where('id', $id)->find();
        if (!$orderInfo) {
            return ['status' => false, "data" => [], 'msg' => '订单不存在'];
        }


        //订单付款判断
        if ($status == 'payed' && $orderInfo['pay_status'] == '20') {
            return ['status' => false, "data" => [], 'msg' => '订单已支付'];
        }

        Db::startTrans();
        $nowTime = time();
        $date = date('Y-m-d', $nowTime);
        $orderSaveData = [];
        try {
            switch ($status) {

                case 'payed'://付款
                    $orderSaveData['pay_status'] = '20';
                    $this->settle($orderInfo);
                    $this->updateUserVip($orderInfo);
                    break;

                default:
                    break;
            }

            //更新状态
            $resv = $this->save($orderSaveData, ["id" => $id]);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ["status" => false, "data" => [], "msg" => $e->getMessage()];
        } catch (\InvalidArgumentException $e) {
            Db::rollback();
            return ["status" => false, "data" => [], "msg" => $e->getMessage()];
        }

        return ["status" => true, "data" => [], "msg" => "操作成功"];
    }

    /**
     * 订单结算
     * @param $orderInfo
     */
    public function settle($orderInfo)
    {

        //业务推广上级
        $pid = $orderInfo->user->parent_user_id;
        if ($pid) {
            $saleUser = XiserviceUser::where("user_id", $pid)->where('group_id', 4)->find();


            //业务提成
            if ($saleUser && $orderInfo['divide_rate']) {
                $dividendMoney = bcmul($orderInfo['pay_money'], ($orderInfo['divide_rate'] / 100), 2);

                //记录销售分成订单
                $dividendData = [
                    'user_id' => $saleUser['user_id'],
                    'order_type' => 'member',
                    'dividend_type' => 'team',
                    'source_order_no' => $orderInfo['order_no'],
                    'total_amount' => $orderInfo['pay_money'],
                    'divide_rate' => $orderInfo['divide_rate'],
                    'divide_money' => $dividendMoney,
                    'extra_data' => '',
                ];
                $did = Dividend::insertGetId($dividendData);

                //记录销售分成
                $benfitdata['type'] = 3;
                $benfitdata['user_id'] = $saleUser['user_id'];
                $benfitdata['order_id'] = $did;
                $benfitdata['scale'] = $orderInfo['divide_rate'] / 100;
                $benfitdata['money'] = $dividendMoney;
                $benfitdata['status'] = 2;
                $benfitdata['createtime'] = time();
                $benfitdata['updatetime'] = time();
                BenfitModel::insertGetId($benfitdata);
                XiserviceUser::where("user_id", $saleUser['user_id'])->setInc("total_money", $dividendMoney);
                XiserviceUser::where("user_id", $saleUser['user_id'])->setInc("can_money", $dividendMoney);
            }
        }
    }

    /**
     * 更新用户vip
     */
    public function updateUserVip($orderInfo)
    {
        $userInfo = XiserviceUser::where("user_id", $orderInfo['user_id'])->find();

        $saveVipData = [
            'vip_type' => $orderInfo['type'],
            'vip_end_time' => 0,
        ];
        if ($userInfo['vip_end_time'] > time()) {
            //原vip服务未到期
            $saveVipData['vip_end_time'] = $userInfo['vip_end_time'] + ($orderInfo['day'] * 24 * 60 * 60);
        } else {
            $saveVipData['vip_end_time'] = time() + ($orderInfo['day'] * 24 * 60 * 60);
        }

        XiserviceUser::where("user_id", $orderInfo['user_id'])->update($saveVipData);
    }
}
